package com.shark.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @auther shark
 * @create 2024-08-08 16:45
 */
//@Component
@Slf4j
public class MyMessageListener4Limit
{
    public static final String EXCHANGE_DIRECT = "exchange.direct.order"; //exchange.direct.order
    public static final String QUEUE_NAME  = "queue.order";
    public static final String ROUTING_KEY = "orderlimit";

    // 修饰监听方法
    @RabbitListener(
            // 设置绑定关系
            bindings = @QueueBinding(
                    // 配置交换机信息：durable 设置为 true 表示队列持久化；autoDelete 设置为 false 表示关闭自动删除
                    exchange = @Exchange(value = EXCHANGE_DIRECT, durable = "true", autoDelete = "false"),

                    // 配置队列信息：durable 设置为 true 表示队列持久化；autoDelete 设置为 false 表示关闭自动删除
                    value = @Queue(value = QUEUE_NAME, durable = "true", autoDelete = "false"),

                    // 配置路由键信息
                    key = {ROUTING_KEY}
            ))
    public void processMessage(String dataString, Message message, Channel channel) throws IOException
    {
        /*
        - Ready表示已经发送到队列的消息数量
        - Unacked表示已经发送到消费端但是消费端尚未返回ACK信息的消息数量
        - Total未被删除的消息总数
        */

        // 1、获取当前消息的 deliveryTag 值备用
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //System.out.println("---deliveryTag: "+deliveryTag);

        // 2、正常业务操作
        log.info("消费端limit：" + dataString);

        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        // 3、给 RabbitMQ 服务器返回 ACK 确认信息
        channel.basicAck(deliveryTag, false);
    }
}
